<template>
  <div>
    <BasicTable
      @register="registerTable"
      :rowSelection="{ type: 'checkbox', selectedRowKeys: checkedKeys, onChange: onSelectChange }"
    >
      <template #headerTop>
        <Alert type="info" show-icon>
          <template #message>
            <template v-if="checkedKeys.length > 0">
              <span>已选中{{ checkedKeys.length }}条记录(可跨页)</span>
              <a-button type="link" @click="checkedKeys = []" size="small">清空</a-button>
            </template>
            <template v-else>
              <span>未选中任何项目</span>
            </template>
          </template>
        </Alert>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'clarity:note-edit-line',
                tooltip: '编辑',
                onClick: handleEdit.bind(null, record),
              },
            ]"
        /></template>
        <template v-else-if="column.key === 'miniProgramVersion'">
          <Button @click="openQrCodeModal(record)" type="link"> 查看 </Button>
        </template>
      </template>
      <template #toolbar>
        <a-button type="primary" @click="handleAdded">{{
          t('routes.institution.institutionList.added')
        }}</a-button>
      </template>
    </BasicTable>
    <Added @register="register" @reload="reload" />
    <BasicModal
      @register="registerModal"
      :showCancelBtn="false"
      :showOkBtn="false"
      title="小程序二维码"
      width="800px"
    >
      <div class="flex flex-col items-center gap-24px">
        <div>小程序二维码</div>
        <Image :src="qrCodeUrl" width="280px" height="280px" />
        <Button
          @click="downloadByUrl({ url: qrCodeUrl, fileName: '小程序二维码.jpg' })"
          type="primary"
          ghost
        >
          下载二维码
        </Button>
      </div>
    </BasicModal>
  </div>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { getBasicColumns } from './tableData';
  import { Alert } from 'ant-design-vue';
  import { getQrcode, list } from '@/api/institution/list';
  import type { ListItem } from '@/api/institution/model/listModel';
  import Dictionary from '@/utils/dictionary';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useDrawer } from '@/components/Drawer';
  import Added from './added.vue';
  import { BasicModal, useModal } from '@/components/Modal';
  import { downloadByUrl } from '@/utils/file/download';
  import { Image, Button } from 'ant-design-vue';
  const dicts = Dictionary.getLocalMulti(['orgType', 'enabled', 'deployType']);

  const checkedKeys = ref<Array<string | number>>([]);

  const { t } = useI18n();
  const [register, { openDrawer }] = useDrawer();

  const [registerTable, { reload }] = useTable({
    title: '开启搜索区域',
    api: list,
    columns: getBasicColumns(),
    formConfig: {
      labelWidth: 100,
      schemas: [
        {
          field: `keyWord`,
          label: `机构名称`,
          component: 'Input',
          colProps: {
            span: 6,
          },
        },
        {
          field: `[startTime, endTime]`,
          label: `创建时间`,
          component: 'RangePicker',
          componentProps: {
            format: 'YYYY-MM-DD HH:mm:ss',
            placeholder: ['开始时间', '结束时间'],
            showTime: { format: 'HH:mm:ss' },
          },
          colProps: {
            span: 8,
          },
        },
        {
          field: `enabled`,
          label: `状态`,
          component: 'Select',
          componentProps: {
            fieldNames: { label: 'dictLabel', value: 'dictValue' },
            options: dicts.enabled,
          },
          colProps: {
            span: 4,
          },
        },
      ],
    },
    useSearchForm: true,
    showTableSetting: true,
    tableSetting: { fullScreen: true },
    showIndexColumn: true,
    clickToRowSelect: false,
    actionColumn: {
      width: 120,
      title: '操作',
      dataIndex: 'action',
    },
    afterFetch: (data: ListItem[]) => {
      return data.map((item) => {
        return {
          ...item,
          orgTypeText: dicts.orgType.find((v) => v.dictValue == item.orgType)?.dictLabel,
          enabledText: dicts.enabled.find((v) => v.dictValue == item.enabled)?.dictLabel,
          deployTypeText: dicts.deployType.find((v) => v.dictValue == item.deployType)?.dictLabel,
          roomSize: `${item.residualSpace || 0}/${item.roomSize || 0}`,
        };
      });
    },
  });

  function onSelectChange(selectedRowKeys: (string | number)[]) {
    checkedKeys.value = selectedRowKeys;
  }

  const qrCodeUrl = ref('');
  const [registerModal, { openModal }] = useModal();
  const openQrCodeModal = async (record: ListItem) => {
    qrCodeUrl.value = '';
    qrCodeUrl.value = await getQrcode(record.id);
    openModal();
  };
  /** 编辑机构 */
  function handleEdit(record: ListItem) {
    openDrawer(true, {
      id: record.id,
    });
  }

  /** 新增机构 */
  function handleAdded() {
    openDrawer(true, {
      id: undefined,
    });
  }
</script>
